package com.cos.lession47.web.controller;

import com.cos.lession47.common.Const;
import com.cos.lession47.util.StringUtil;
import lombok.extern.log4j.Log4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author: COS
 * @time: 2022/2/28 11:14
 * @description:
 */
public class BaseServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String type = request.getParameter("type");
        if (!StringUtil.isNotEmpty(type)) {
            response.sendRedirect(request.getContextPath()+"/index.jsp");
        }
        try {
            //获取类对象
            Class<? extends BaseServlet> aClass = this.getClass();
            //获取方法对象
            Method method = aClass.getMethod(type, HttpServletRequest.class, HttpServletResponse.class);
            //调用方法
            String invoke = (String) method.invoke(this, request, response);
            //判断处理
            if (invoke.contains(Const.FORWARD)) {
                String path = invoke.split(":")[1];
                request.getRequestDispatcher(path).forward(request, response);
            }else if (invoke.contains(Const.REDIRECT)) {
                String path = invoke.split(":")[1];
                response.sendRedirect(request.getContextPath()+"/"+path);
            }else{
                response.getWriter().write(invoke);
            }
        } catch (Exception e) {
            e.printStackTrace();
            response.sendRedirect(request.getContextPath()+"/index.jsp");
        }
    }
}
